package com.engine.ld.optimize;

import com.weaver.general.BaseBean;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weaver.conn.RecordSet;
import weaver.soa.workflow.request.RequestInfo;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;

/**
 * @author ZhangLei
 * @date 2021/6/24
 * 工具领用
 */
public class Gjly {
    private static final BaseBean bb = new BaseBean();

    public String GjlyXml(String requestid, RequestInfo requestInfo){
        bb.writeLog("进入工具领用XML组装");

        String mainSql = "select BLDAT,BUDAT,BKTXT,ACTION,BWART,REFDOC from formtable_main_152 where requestid = "+requestid;
        String dtSql = "select MATNR,ERFMG,WERKS,ERFME,LGORT,CHARG,KOSTL,AUFNR,SGTXT" +
                " from formtable_main_152 a left join formtable_main_152_dt1 b " +
                "on a.id = b.mainid where requestid = "+requestid;
        bb.writeLog("删除的SQL是："+dtSql);
//        从数据库中获取数据并组装成XML
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document document = builder.newDocument();
        Element root = document.createElement("ROOT");
        document.appendChild(root);
//        组装HEAD节点
        Element head = document.createElement("HEAD");
        RecordSet mainRs = new RecordSet();
        mainRs.executeQuery(mainSql);
        if (mainRs.next()){
            appendChild(document,head,"BLDAT",mainRs.getString("BLDAT"));
            appendChild(document,head,"BUDAT",mainRs.getString("BUDAT"));
            appendChild(document,head,"BKTXT",mainRs.getString("BKTXT"));
            appendChild(document,head,"ACTION",mainRs.getString("ACTION"));
            appendChild(document,head,"BWART",mainRs.getString("BWART"));
            appendChild(document,head,"REFDOC",mainRs.getString("REFDOC"));
        }
        root.appendChild(head);
//        组装ITEM节点
        Element item = document.createElement("ITEM");
        RecordSet dtRs = new RecordSet();
        dtRs.executeQuery(dtSql);
        while (dtRs.next()){
//            bb.writeLog("dtRs.next()的结果是true");
//            bb.writeLog("where情况下获取MATNR节点的值："+dtRs.getString("MATNR"));
            appendChild(document,item,"MATNR",dtRs.getString("MATNR"));
            appendChild(document,item,"ERFMG",dtRs.getString("ERFMG"));
            appendChild(document,item,"WERKS",dtRs.getString("WERKS"));
            appendChild(document,item,"ERFME",dtRs.getString("ERFME"));
            appendChild(document,item,"LGORT",dtRs.getString("LGORT"));
            appendChild(document,item,"CHARG",dtRs.getString("CHARG"));
            appendChild(document,item,"KOSTL",dtRs.getString("KOSTL"));
            appendChild(document,item,"AUFNR",dtRs.getString("AUFNR"));
            appendChild(document,item,"SGTXT",dtRs.getString("SGTXT"));
        }
        root.appendChild(item);
        bb.writeLog("传给SAP的参数是："+createXmlToString(document));

        return createXmlToString(document);
    }

    /**
     * document对象中添加子项
     *
     * @param document ducument对象
     * @param parent   父元素
     * @param key      元素标签
     * @param value    元素content值
     */
    private static void appendChild(Document document, Element parent, String key, String value) {
        Element child = document.createElement(key);
        if (child != null) {
            child.setTextContent(value);
        }
        parent.appendChild(child);
    }

    /**
     * 生成xml字符串
     *
     * @param document Document树对象
     * @return 整个xml字符串
     */
    private static String createXmlToString(org.w3c.dom.Document document) {
        String xmlString = null;
        try {
            // 创建TransformerFactory工厂对象
            TransformerFactory transFactory = TransformerFactory.newInstance();
            // 通过工厂对象, 创建Transformer对象
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
            //使Xml自动换行, 并自动缩进
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  //中间的参数网址固定写法(这里还没搞懂)
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");                          //是否设置缩进（indent: yes|no）
            // 创建DOMSource对象并将Document加载到其中
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 使用Transformer的transform()方法将DOM树转换成XML
            transformer.transform(domSource, new StreamResult(bos));
            xmlString = bos.toString();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return xmlString;
    }
}
